package com.wangzhen.exchangesTwo.config;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author 死信队列监听
 * * 接收delay对了ttl超时的消息
 * @create 2020-04-14 17:35
 */
@Component
public class DeadLetterMessageReceiver {
    public static final Logger log = LoggerFactory.getLogger(DeadLetterMessageReceiver.class);

    @RabbitListener(queues = RabbitMQConfig.DEAD_LETTER_REALTIMEMSG_NAME)
    public void receiveA(Message message, Channel channel) throws IOException {
        System.out.println("收到死信realtimemsg：" + new String(message.getBody()));
        System.out.println("收到死信realtimemsg：" + message.getMessageProperties().getDeliveryTag());
        String msg = new String(message.getBody());
        log.info("收到死信realtimemsg：{}", msg);
        boolean ack = true;
        Exception exception = null;
        try {
            //处理业务逻辑
        } catch (Exception e) {
            ack = false;
            exception = e;
        }
        //判断ack是否报错则加入死信队列
        if (ack) {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
        } else {
            log.error("消息消费发生异常，error msg:{}", exception.getMessage(), exception);
            //三个参数，第一个是回复标识，第三个是是否重回队列
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
        }
    }

    @RabbitListener(queues = RabbitMQConfig.DEAD_LETTER_OTHERMSG_NAME)
    public void receiveB(Message message, Channel channel) throws IOException {

        String msg = new String(message.getBody());
        log.info("收到死信othermisg：{}", msg);
        boolean ack = true;
        Exception exception = null;
        try {
            //处理业务
        } catch (Exception e) {
            ack = false;
            exception = e;
        }
        //判断ack是否报错则加入死信队列
        if (ack) {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
        } else {
            log.error("消息消费发生异常，error msg:{}", exception.getMessage(), exception);
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
        }
    }
}
